THRESHOLD = (0, 100, 37, 127, 1, 127)
ROID=[80,0,160,240]

import sensor, image, time, math
from pyb import UART, LED

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
#sensor.set_auto_gain(False)  # must turn this off to prevent image washout...
#sensor.set_auto_whitebal(False)  # must turn this off to prevent image washout...
#False True
clock = time.clock()

state = 0
d=None
b=0
#None
uart = UART(3,115200)
uart.init(115200, bits=8, parity=None, stop=1)

def find_max(blobs):
    max_size=0
    for blob in blobs:
        if blob.pixels() > max_size:
            max_blob=blob
            max_size = blob.pixels()
    return max_blob

while(True):
    clock.tick()
    a = None
    if(uart.any()>0):
       c=uart.readchar()
       if state==0:
           if c == 33:#帧头
               state = 1
               #print(c)
           else:
               state = 0
       elif state==1:
           d=c
           state = 2
       elif state == 2:
           if c == 35:
               a=d
               state = 0
           else:
               state = 0
               d=None
               a=None
       else:
           state = 0
           d=None
           a=None
    if a=="1":
        d=1
    elif a=="2":
        d=2
    #d=49
    if d==50 or d==None:
        #print(d)
        sensor.set_pixformat(sensor.RGB565)
        sensor.set_framesize(sensor.QVGA)
        sensor.set_auto_gain(True)
        sensor.set_auto_whitebal(True)
        img = sensor.snapshot()
        blobs = img.find_blobs([THRESHOLD],roi=ROID)
        if blobs :
            LED(1).on()
            LED(2).on()
            LED(3).on()
            max_blob=find_max(blobs)
            img.draw_rectangle(max_blob.rect())
            img.draw_cross(max_blob.cx(), max_blob.cy())
            img.draw_rectangle(ROID)
            output_str =str(int(max_blob.cx()/320*255))
            uart.write('$'+'?'+output_str+'>')
            print(output_str,max_blob.pixels())
    elif d==49:
        sensor.set_pixformat(sensor.GRAYSCALE)
        sensor.set_framesize(sensor.VGA)
        sensor.set_auto_gain(False)
        sensor.set_auto_whitebal(False)
        img = sensor.snapshot()
        codes = img.find_barcodes()
        if codes :
            LED(1).off()
            LED(2).off()
            LED(3).off()
            for code in codes:
                img.draw_rectangle(code.rect())
                message=str(code.payload())
                uart.write('#'+'%'+message+'!')
                print(message,b)
                b=b+1
    time.sleep_ms(100)



















